import re

from django.conf import settings
from django.contrib.auth.backends import ModelBackend

from apps.users.models import User
from meiduo_mall.utils.secret import SecretOauth


# 2.生成激活链接
def generate_verify_email_url(request):
    # 1.user_id email
    data_dict = {
        'user_id': request.user.id,
        'email': request.user.email
    }
    # 2.将参数加密
    dumps_data = SecretOauth().dumps(data_dict)

    # 3.拼接 完整的激活路由
    verify_url = settings.EMAIL_VERIFY_URL + dumps_data

    return verify_url


# 封装函数
def get_user_by_account(account):
    try:
        if re.match('^1[3-9]\d{9}$', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except Exception as e:
        print(e)
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 1.根据账号  查询user
        user = get_user_by_account(username)

        # 2.校验密码
        if user and user.check_password(password):
            return user
